const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command;

const MAX_LIMIT = 100;

// 默认每次选取前15条数据

exports.main = async (event, context) => {

  const wxContext = cloud.getWXContext()
  
  const user = await db.collection("user").where({
    openid:wxContext.OPENID,
  }).get()

  console.log(user)
  if(user.data.length == 0)
  {
    
    return {
      code:401,
      data:{},
      msg:"have not login"
   }
  }
  
  if(user.data[0].status != 0 && user.data[0].status != 1)
  {
    return {
      code:401,
		 data:{},
		 msg:"no privilege"
    }
  }
  let timestamp = new Date(new Date().setHours(20,0,0,0)).valueOf()
  //处理拉取但是未处理的预约记录
  const resul = await db.collection("order").where({
    state:3,
    timestamp:_.gt(timestamp)
  }).field({
    _id:true,
    timestamp:true,
    sid:true,
    name:true,
    judge_person:true,
    reserve_reason:true
  }).get()

  if(resul.data.length != 0)
  {
    return {
      code:200,
      data:resul.data,
      msg:"请先完成之前的审核"
    }
  }
  //标记15条记录为正在审核
  const re = await db.collection("order").where({
    state:2,
    timestamp:_.gt(timestamp)
  }).orderBy("timestamp","asc").limit(15).update({
    data:{
      state:3,
      judge_person:user.data[0].name,
      judge_sid:user.data[0].sid
    }
  })
  //拉取刚才标记的15条记录
  const result = await db.collection("order").where({
    state:3,
    sid:user.data[0].sid
  }).field({
    _id:true,
    timestamp:true,
    sid:true,
    name:true,
    judge_person:true,
    reason:true,
    reserve_reason:true

  }).get()

  if(result.data.length == 0)
  {
    return {
      code:404,
      dat:{},
      msg:"已经完成审核啦!"
    }
  }

  return {
    code:200,
    data:result.data,
    msg:"拉取成功",
    timestamp:timestamp
  }

  
};
